import os
from flask import Blueprint, request, render_template, jsonify, current_app

from apps.common.utils.http import fail_api, success_api, table_api
from apps.common.utils.rights import authorize
from apps.extensions import db
from apps.modules.admin.models import Photo
from apps.common.utils import upload as upload_curd

file_bp = Blueprint('adminFile', __name__, url_prefix='/file')


#  图片管理
@file_bp.get('/')
@authorize("system:file:main")
def index():
    return render_template('system/photo/photo.html')


#  图片数据
@file_bp.get('/table')
@authorize("system:file:main")
def table():
    page = request.args.get('page', type=int)
    limit = request.args.get('limit', type=int)
    name = request.args.get('name', '')
    mime = request.args.get('mime', '')
    data, count = upload_curd.get_photo(page=page, limit=limit, name=name, mime=mime)
    return table_api(data=data, count=count)


#   上传
@file_bp.get('/upload')
@authorize("system:file:add", log=True)
def upload():
    return render_template('system/photo/photo_add.html')


#   上传接口
@file_bp.post('/upload')
@authorize("system:file:add", log=True)
def upload_api():
    if 'file' in request.files:
        file = request.files['file']
        mime = file.content_type
        
        # 获取文件类型参数，默认为自动检测
        file_type = request.form.get('file_type', 'auto')
        
        try:
            if file_type == 'auto':
                # 自动检测文件类型
                file_type = upload_curd.get_file_type_by_extension(file.filename)
            
            # 检查文件是否允许上传
            if not upload_curd.is_allowed_file(file.filename, file_type):
                return fail_api(msg=f"不支持的文件类型: {file.filename}")
            
            # 上传文件
            result = upload_curd.upload_file_by_type(file=file, mime=mime, file_type=file_type)
            
            res = {
                "msg": "上传成功",
                "code": 0,
                "success": True,
                "data": {
                    "src": result['url'],
                    "filename": result['filename'],
                    "size": result['size'],
                    "type": result['type']
                }
            }
            return jsonify(res)
        except Exception as e:
            return fail_api(msg=f"上传失败: {str(e)}")
    
    return fail_api(msg="没有选择文件")


#    图片删除
@file_bp.route('/delete', methods=['GET', 'POST'])
@authorize("system:file:delete", log=True)
def delete():
    _id = request.form.get('id')
    res = Photo.query.filter_by(id=_id).delete()
    if res:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg="删除失败")


# 图片批量删除
@file_bp.route('/batchRemove', methods=['GET', 'POST'])
@authorize("system:file:delete", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')

    photo = Photo.query.filter(Photo.id.in_(ids)).delete()
    db.session.commit()
    if photo:
        return success_api(msg="删除成功")
    else:
        return fail_api(msg="删除失败")
